;
(function (window, angular) {
    'use strict';
    angular.module("Controller.BasicData.Materiel", ['ngImgCrop'])
        .controller("MaterielCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "EventBus", "UserContextService", "Upload", "ybConfig", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, EventBus, UserContextService, Upload, ybConfig) {

            $scope.activeFlag = [true, false, false, false, false, false];
            $scope.detailFlag = [true, true, true];
            $scope.markInfo = {
                allChecked: false,
                curMaterialRow: -1,
                curLocationRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.locationPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.locationLogPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            $scope.condition = {};
            $scope.conditionLocationLog = {};
            $scope.dataList = [];
            $scope.detailInfo = {
                isGroupPur: 0,
                crucialDevice: 0,
                entranceDevice: 0,
                isDirectCast: 0,
                authDevice: 0,
                validFlag: 0,
                regeneration: 0,
                vendorSuppliedProduct: 0,
                isTransportRestrict:0,
                isJckMat:0,
                dgCode:0,
                materialsRelationList: [],
            };
            $scope.materialInfo = {};
            $scope.locationList = [];
            $scope.locationLogList = [];
            $scope.tableConfig = {
                fixedWidth: $scope.curOrg.companyType == 1 ? 180 : 110,
                scrollWidth: 1770,
                tableCol: [
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "零件英文描述",
                        dataField: "materialsDesEn",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "零件分类",
                        dataField: "materialsType",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "基本计量单位",
                        dataField: "unit",
                        width: 110,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "标准价",
                        dataField: "standardPrice",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "代理商采购基准价",
                        dataField: "agentPurchasePrice",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "零售目录指导价",
                        dataField: "guidePrice",
                        width: 140,
                        isShow:true,
                        isFixed: false,
                    },
                    {
                        name: "平均价",
                        dataField: "parityPrice",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "无效标记",
                        dataField: "validFlagShow",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: $scope.curOrg.companyType == 1 ? 140 : 70,
                        isShow: true,
                        isFixed: true,
                    }
                ]
            };
            $scope.locationTbConf = {
                scrollWidth: 590,
                tableCol: [
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "仓库",
                        dataField: "warehouseCode",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "库区",
                        dataField: "areaCode",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "储位",
                        dataField: "locationCode",
                        width: 200,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.locationLogTbConf = {
                scrollWidth: 1000,
                tableCol: [
                    {
                        name: "零件编号",
                        dataField: "materialNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "零件中文名",
                        dataField: "materialDesc",
                        width: 220,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "原默认储位",
                        dataField: "oldLocation",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "新默认储位",
                        dataField: "newLocation",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "变更时间",
                        dataField: "operateDateShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "操作人",
                        dataField: "operateUser",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                ]
            };
            $scope.exportParam = {
                sectionParam: { materialsIds: [], materialCodes: [] },
                sectionUrl: ybHttp.RequestUrl("device", "/materials/export"),
                allUrl: ybHttp.RequestUrl("device", "/materials/exportAll"),
            };

            var btnPermissionCode = {
                materielAdd: window.ActionCode.materielAdd,
                materielEdit: window.ActionCode.materielEdit,
                materielDel: window.ActionCode.materielDel,
                materielUpdate: window.ActionCode.materielUpdate,
                materielFromSAP: window.ActionCode.materielFromSAP,
                materielImport: window.ActionCode.materielImport,
                materielExport: window.ActionCode.materielExport,
                materielPlaceImport: window.ActionCode.materielPlaceImport,
                materielReplaceImport: window.ActionCode.materielReplaceImport,
                materielLocation: window.ActionCode.materielLocation,
                showCostPrice: window.ActionCode.showCostPrice,
                materialImportPrice: window.ActionCode.materialImportPrice,
                materialAuthDevice: window.ActionCode.materialAuthDevice,
                materialSetAuthDevice: window.ActionCode.materialSetAuthDevice,
				materialSyncPrice: window.ActionCode.materialSyncPrice,
				materialSyncDescEn: window.ActionCode.materialSyncDescEn,
                purchaseGroup: window.ActionCode.purchaseGroup,
                materialsPropClass: window.ActionCode.materialsPropClass,
                materialPandM: window.ActionCode.materialPandM,
                materialAorB: window.ActionCode.materialAorB,
                importIOReplaceMaterials: window.ActionCode.importIOReplaceMaterials,
                editMaterialsType: window.ActionCode.editMaterialsType,
                importMaterialsType: window.ActionCode.importMaterialsType,
                editMaterialsTypeLogView: window.ActionCode.editMaterialsTypeLogView,
            };

            $scope.btnPermission = {
                materielAdd: true,
                materielEdit: true,
                materielDel: true,
                materielUpdate: true,
                materielFromSAP: true,
                materielImport: true,
                materielExport: true,
                materielPlaceImport: true,
                materielReplaceImport: true,
                materielLocation: true,
                showCostPrice: true,
                materialImportPrice: true,
                materialAuthDevice: true,
                materialSetAuthDevice: true,
				materialSyncPrice: true,
				materialSyncDescEn: true,
                purchaseGroup: true,
                materialsPropClass: true,
                materialPandM: true,
                materialAorB: true,
                importIOReplaceMaterials: true,
                editMaterialsType: false,
                importMaterialsType: false,
                editMaterialsTypeLogView: false,
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }


            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    scrollLeft: { left: $scope.tableConfig.fixedWidth + "px" },
                    scrollLeftWidth: { width: $scope.tableConfig.fixedWidth + "px" }
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false, false];
                $scope.activeFlag[index] = true;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.detailInfo = {
                    isGroupPur: 0,
                    crucialDevice: 0,
                    entranceDevice: 0,
                    isDirectCast: 0,
                    authDevice: 0,
                    validFlag: 0,
                    regeneration: 0,
                    vendorSuppliedProduct: 0,
                    isTransportRestrict:0,
                    isJckMat:0,
                    dgCode:0,
                    materialsRelationList: [],
                    productPropClass:''
                };
                $scope.detailFlag = [true, true, true];
                $scope.locationList = [];
                $scope.conditionLocationLog = {};
            }

            function getDataList(curPage) {
                $scope.markInfo.allChecked = false;
                $scope.markInfo.curMaterialRow = -1;
                $scope.exportParam.sectionParam.materialsIds = [];
                $scope.exportParam.sectionParam.materialCodes = [];
                var service = "device";
                var reqUrl = "/materials/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.groupPurShow = $filter("TrueOrFalse")(item.isGroupPur);
                        item.entranceDeviceShow = $filter("TrueOrFalse")(item.entranceDevice);
                        item.crucialDeviceShow = $filter("TrueOrFalse")(item.crucialDevice);
                        item.isDirectCastShow = $filter("TrueOrFalse")(item.isDirectCast);
                        item.authDeviceShow = $filter("TrueOrFalse")(item.authDevice);
                        item.validFlagShow = $filter("TrueOrFalse")(item.validFlag);

                        if ($scope.isZHJCH) {
                            item.hasImg = !!item.orgImageUrl ? "是" : "否";
                        } else {
                            item.hasImg = (!!item.orgImageUrl || !!item.dealerImageUrl) ? "是" : "否";
                        }
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }

            };

            $scope.selectRow = function (index, type) {
                $scope.markInfo["cur" + type + "Row"] = index;
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };
            $scope.resetLocationLog = function () {
                $scope.conditionLocationLog = {};
            };

            $scope.switchDetailBar = function (index) {
                $scope.detailFlag[index] = !$scope.detailFlag[index];
            };

            $scope.getMaterialsInfo = function () {
                $scope.exportParam.sectionParam.materialsIds = [];
                $scope.exportParam.sectionParam.materialCodes = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.materialsIds.push(item.materialsId);
                        $scope.exportParam.sectionParam.materialCodes.push(item.materialsNo);
                    }
                });
            };

            $scope.selectAll = function () {
                angular.forEach($scope.dataList, function (item) {
                    item.isChecked = $scope.markInfo.allChecked;
                });
                $scope.getMaterialsInfo();
            };

            function checkAll() {
                var selectAll = false;
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!$scope.dataList[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectSingle = function (item) {
                if (!item.isChecked) {
                    $scope.markInfo.allChecked = false;
                } else {
                    if (!checkAll()) {
                        $scope.markInfo.allChecked = false;
                    } else {
                        $scope.markInfo.allChecked = true;
                    }
                }
                $scope.getMaterialsInfo();
            };

            function getDetail(item) {
                var service = "device";
                var reqUrl = "/materials/item";
                var param = {};
                param.materialsId = item.materialsId;
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    var data = resp.value || {};
                    data.orgImageUrl = item.orgImageUrl;
                    data.dealerImageUrl = item.dealerImageUrl;
                    data.gsImgurlList = data.gsImgurl ? UserContextService.GetYbUpLoadObjConstructor([data.gsImgurl]) : [];
                    return data;
                });
            }

            function viewDetail(item) {
                getDetail(item).then(function (data) {
                    $scope.detailInfo = data;
                    $scope.detailInfo.minimumBuy = $scope.detailInfo.isMinimumBuy ? $scope.detailInfo.minimumBuy : '';
                    $scope.detailInfo.materialsGradeVO = {
                        code: data.gradeId,
                        name: data.grade
                    };

                    if (data.orgImageUrl) {
                        $scope.detailInfo.orgImageUrlList = UserContextService.GetYbUpLoadObjConstructor(data.orgImageUrl.split(','));
                    }
                    if (data.dealerImageUrl) {
                        $scope.detailInfo.dealerImageUrlList = UserContextService.GetYbUpLoadObjConstructor(data.dealerImageUrl.split(','));
                    }

                    $scope.changeTab(2);
                });
            }

            $scope.viewLocation = function (item) {
                $scope.materialInfo = { materialNo: item.materialsNo, materialsDes: item.materialsDes };
                
                $scope.searchLocation(1).then(res => {
                    if (res) {
                        $scope.changeTab(3);
                    }
                })
                
            };

            $scope.searchLocation = function (curPage) {
                $scope.markInfo.curLocationRow = -1;
                var service = "device";
                var reqUrl = "/materials/locationRelationList";
                if (!!curPage) {
                    $scope.locationPageInfo.curPage = curPage;
                }
                var param = {
                    pageSize: $scope.locationPageInfo.pageSize,
                    pageNum: $scope.locationPageInfo.curPage,
                    filters: { materialNo: $scope.materialInfo.materialNo }
                };
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    $scope.locationList = resp.value.list;
                    $scope.locationPageInfo.totalRows = resp.value.total;
                    $scope.locationPageInfo.totalPages = resp.value.pages;
                    return true;
                });
            };

            $scope.viewLocationLog = function() {
                $scope.searchLocationLog(1).then(res => {
                    if (res) {
                        $scope.changeTab(8);
                    }
                })
            };

            $scope.searchLocationLog = function (curPage) {
                var service = "device";
                var reqUrl = "/materialLocationLog/list";
                if (!!curPage) {
                    $scope.locationLogPageInfo.curPage = curPage;
                }
                var param = {
                    pageSize: $scope.locationLogPageInfo.pageSize,
                    pageNum: $scope.locationLogPageInfo.curPage,
                    filters: {
                        materialNo: $scope.materialInfo.materialNo,
                        ...$scope.conditionLocationLog
                    }
                };
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.operateDateShow = $filter("YbDate")(item.operateDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.locationLogList = resp.value.list;
                    $scope.locationLogPageInfo.totalRows = resp.value.total;
                    $scope.locationLogPageInfo.totalPages = resp.value.pages;
                    return true;
                });
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.importLocation = function () {
                var param = {
                    name: "储位",
                    templateReqService: "device",
                    templateReqUrl: "/materials/downloadLocationExcel",
                    importReqService: "device",
                    importReqUrl: "/materials/importLocationExcel",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getDataList(1);
                });
            };

            /*
            * ======================供应商列表开始==========================
            * */
            $scope.supplierMarkInfo = {
                allChecked: false,
                curMaterialRow: -1,
                curLocationRow: -1
            };
            $scope.supplierPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };

            var materielObj = "";

            $scope.supplierCondition = {};
            $scope.supplierDataList = [];
            $scope.supplierTableConfig = {
                fixedWidth: 0,
                scrollWidth: 900,
                tableCol: [
                    {
                        type: "",
                        name: "供应商名称",
                        dataField: "supplierComName",
                        width: 200,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "供应商orgId",
                        dataField: "supplierOrgId",
                        width: 110,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "供应商代码",
                        dataField: "supplierCode",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 80,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            $scope.supplierSearch = function (curpage) {
                getSupplierDataList(curpage);
            };

            $scope.supplierReset = function () {
                $scope.supplierCondition = {
                    materialsNo: materielObj.materialsNo,
                    arrFactory: materielObj.arrFactory,
                };
            };

            $scope.viewSupplier = function (item) {
                materielObj = item;
                $scope.supplierCondition = {
                    materialsNo: materielObj.materialsNo,
                    arrFactory: materielObj.arrFactory,
                };
                getSupplierDataList();
                $scope.setSupplierFixedWidth();
                $scope.changeTab(4);
            };

            $scope.setSupplierFixedWidth = function () {
                $scope.supplierTbStyle = { scrollLeft: { left: $scope.supplierTableConfig.fixedWidth + "px" } };
            };

            function getSupplierDataList(curPage) {
                $scope.supplierMarkInfo.allChecked = false;
                $scope.supplierMarkInfo.curMaterialRow = -1;
                var service = "device";
                var reqUrl = "/materials/querySupplierList";
                var param = {};
                param.pageSize = $scope.supplierPageInfo.pageSize;
                if (!!curPage) {
                    $scope.supplierPageInfo.curPage = curPage;
                }
                param.pageNum = $scope.supplierPageInfo.curPage;
                param.filters = angular.copy($scope.supplierCondition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.createTimeStr = $filter("YbDate")(item.createTime, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.supplierPageInfo.totalRows = resp.value.total;
                    $scope.supplierPageInfo.totalPages = resp.value.pages;
                    $scope.supplierDataList = resp.value.list;
                });
            }

            $scope.delSupplier = function (item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/materialsSupplier/remove";
                    ybHttp.Get(service, reqUrl, { id: item.id }).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getSupplierDataList();
                    });
                });
            };

            $scope.addDefaultLocation = function() {
                ybWidget.ShowConfirm("新增默认储位", "储位", { isTextarea: false }).then((val) => {
                    ybHttp.Post("device", "/materials/addLocation", {
                        materialNo: $scope.materialInfo.materialNo,
                        locationCode: val
                    }).then((resp) => {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.searchLocation(1);
                    })
                })
            };


            (function () {
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
                getDataList();
            })();
        }])
        ;
})(window, window.angular);
